<?php

namespace App\Kuafu\Base\Util;

class DateTimeUtil
{
    /**
     * 时间转换，把12:00或者23:59:59 转成秒数
     * @param $clockStr
     * @return int|null  范围0 ~ 86439
     */
    public static function clockToSeconds($clockStr): ?int
    {
        $arr = explode(':', $clockStr);
        switch (count($arr)) {
            case 2:
                // 12:00
                return 3600 * $arr[0] + 60 * $arr[1];
            case 3:
                // 23:59:59
                return 3600 * $arr[0] + 60 * $arr[1] + $arr[2];
        }
        return null;
    }

    /**
     * 时间转换，把0 ~ 86439 转成是时分
     * @param $seconds
     * @return string
     */
    public static function secondsToClock($seconds)
    {
        if (floor($seconds / 3600)) {
            $h = (int)floor($seconds / 3600);
        } else {
            $h = "00";
        }
        $m = (int)($seconds - $h * 3600) / 60;
        if (strlen($h) == 1) {
            $h = '0' . $h;
        }
        if (strlen($m) == 1) {
            $m = '0' . $m;
        }
        return $h . ":" . $m;
    }

    /**
     * 判断是否为合法日期，格式：2021-01-01
     * @param $date
     * @return bool
     */
    public static function isBaseDate($date): bool
    {
        $date = (string)$date;
        if (10 != strlen($date)) {
            return false;
        }
        return date('Y-m-d', strtotime($date)) === $date;
    }
}
